package org.tao.lightningmq.nameserver.event.spi.listener;

import com.alibaba.fastjson2.JSON;
import io.netty.channel.ChannelHandlerContext;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.tao.lightningmq.common.dto.HeartBeatDTO;
import org.tao.lightningmq.common.enums.NameServerResponseCode;
import org.tao.lightningmq.common.event.Listener;
import org.tao.lightningmq.common.tcp.TcpMsg;
import org.tao.lightningmq.nameserver.event.model.SlaveHeartBeatEvent;

/**
 * @Author lht
 * @date 2025/1/16 - 21:38
 * @description: 从节点心跳监听器
 */
public class SlaveHeartBeatListener implements Listener<SlaveHeartBeatEvent> {

    private static final Logger LOGGER = LoggerFactory.getLogger(SlaveHeartBeatListener.class);

    @Override
    public void onReceive(SlaveHeartBeatEvent event) throws Exception {
        ChannelHandlerContext context = event.getContext();
        // 发送消息给到客户端
        HeartBeatDTO heartBeatDTO = new HeartBeatDTO();
        heartBeatDTO.setMsgId(event.getMsgId());
        context.writeAndFlush(new TcpMsg(NameServerResponseCode.HEART_BEAT_SUCCESS,
                JSON.toJSONBytes(heartBeatDTO)));

        if (LOGGER.isDebugEnabled()) {
            LOGGER.debug("接收到从节点心跳信号, msgId: {}", event.getMsgId());
        }
    }
}
